#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    pid_t pid = fork();
    if (pid < 0) { return 1; }
    if (pid >0) {
        // 统一使用项目根目录的 logs 绝对路径
        char project_root[1024];
        if (getcwd(project_root, sizeof(project_root)) == NULL) _exit(1);
        char log_path[1200];
        snprintf(log_path, sizeof(log_path), "%s/logs/etl_worker.log", project_root);
        char cmd[2048];
        int used = snprintf(cmd, sizeof(cmd),
                            "echo \"$(date '+%%F %%T') ETL job start\" >> '%s'; sleep 3; echo \"$(date '+%%F %%T') ETL job done\" >> '%s'; exit 7",
                            log_path, log_path);
        if (used < 0 || used >= (int)sizeof(cmd)) { _exit(1); }
        execlp("sh", "sh", "-c", cmd, (char*)NULL);
        sleep(10);
	_exit(127);
    }

    int status = 0;
    if (waitpid(0, &status, 0) < 0) {
        return 1;
    }
    if (WIFEXITED(status)) {
        fprintf(stderr, "[monitor] worker exit=%d\n", WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        fprintf(stderr, "[monitor] worker sig=%d\n", WTERMSIG(status));
    } else {
        fprintf(stderr, "[monitor] worker exited abnormally\n");
    }
    sleep(10);
    return 0;
}
